<template>
  <div class="todo-container">
    <div class="page-header">
      <h2>我的待办</h2>
      <p>查看和处理您的待办任务</p>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
      <el-card>
        <el-form :model="queryParams" ref="queryFormRef" :inline="true">
          <el-form-item label="任务名称" prop="taskName">
            <el-input
              v-model="queryParams.taskName"
              placeholder="请输入任务名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          
          <el-form-item label="流程名称" prop="processName">
            <el-input
              v-model="queryParams.processName"
              placeholder="请输入流程名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          
          <el-form-item label="优先级" prop="priority">
            <el-select
              v-model="queryParams.priority"
              placeholder="请选择优先级"
              clearable
              style="width: 150px"
            >
              <el-option label="高" value="1" />
              <el-option label="中" value="2" />
              <el-option label="低" value="3" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="任务状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              clearable
              style="width: 150px"
            >
              <el-option label="全部" value="" />
              <el-option label="待签收" value="CREATED_CANDIDATE" />
              <el-option label="待认领" value="CREATED" />
              <el-option label="已认领" value="ASSIGNED" />
              <el-option label="进行中" value="PENDING" />
              <el-option label="已完成" value="COMPLETED" />
              <el-option label="已取消" value="CANCELLED" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              v-model="queryParams.createTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 240px"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleQuery">
              <Icon icon="ant-design:search-outlined" />
              查询
            </el-button>
            <el-button @click="resetQuery">
              <Icon icon="ant-design:reload-outlined" />
              重置
            </el-button>
            <el-button @click="toggleAdvancedFilter">
              <Icon icon="ant-design:filter-outlined" />
              {{ showAdvancedFilter ? '收起' : '高级筛选' }}
            </el-button>
          </el-form-item>
        </el-form>
        
        <!-- 高级筛选 -->
        <el-collapse-transition>
          <div v-show="showAdvancedFilter" class="advanced-filter">
            <el-divider />
            <el-form :model="advancedQueryParams" :inline="true">
              <el-form-item label="到期时间" prop="dueTime">
                <el-date-picker
                  v-model="advancedQueryParams.dueTime"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  style="width: 240px"
                />
              </el-form-item>
              
              <el-form-item label="是否过期" prop="isOverdue">
                <el-select
                  v-model="advancedQueryParams.isOverdue"
                  placeholder="请选择"
                  clearable
                  style="width: 120px"
                >
                  <el-option label="已过期" value="true" />
                  <el-option label="未过期" value="false" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="任务类型" prop="taskType">
                <el-select
                  v-model="advancedQueryParams.taskType"
                  placeholder="请选择任务类型"
                  clearable
                  style="width: 150px"
                >
                  <el-option label="用户任务" value="userTask" />
                  <el-option label="服务任务" value="serviceTask" />
                  <el-option label="脚本任务" value="scriptTask" />
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </el-collapse-transition>
      </el-card>
    </div>

    <!-- 任务统计 -->
    <div class="stats-section">
      <el-row :gutter="16">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon pending">
                <Icon icon="ant-design:clock-circle-outlined" />
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ taskStats.pending }}</div>
                <div class="stat-label">待处理</div>
                <div class="stat-detail">
                  <span class="detail-item">{{ taskStats.candidate }}人待签收</span>
                  <span class="detail-item">{{ taskStats.assigned }}人已认领</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon candidate">
                <Icon icon="ant-design:team-outlined" />
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ taskStats.candidate }}</div>
                <div class="stat-label">待签收</div>
                <div class="stat-detail">候选人任务</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon overdue">
                <Icon icon="ant-design:exclamation-circle-outlined" />
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ taskStats.overdue }}</div>
                <div class="stat-label">已过期</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon total">
                <Icon icon="ant-design:file-text-outlined" />
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ taskStats.total }}</div>
                <div class="stat-label">总任务</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 任务列表 -->
    <div class="task-section">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>待办任务列表</span>
            <div class="header-actions">
              <el-button 
                v-if="selectedRows.length > 0"
                type="warning" 
                @click="handleBatchClaim"
                :disabled="!canBatchClaim"
              >
                <Icon icon="ant-design:check-outlined" />
                {{ getBatchActionText() }} ({{ selectedRows.length }})
              </el-button>
              <el-button 
                v-if="selectedRows.length > 0"
                type="info" 
                @click="handleBatchDelegate"
              >
                <Icon icon="ant-design:user-switch-outlined" />
                批量委派 ({{ selectedRows.length }})
              </el-button>
              <el-button type="primary" @click="refreshList">
                <Icon icon="ant-design:reload-outlined" />
                刷新
              </el-button>
            </div>
          </div>
        </template>

        <el-table
          v-loading="loading"
          :data="taskList"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          
          <el-table-column prop="taskName" label="任务名称" min-width="120" max-width="160">
            <template #default="scope">
              <div class="task-name-cell">
                <Icon icon="ant-design:check-square-outlined" class="task-icon" />
                <el-tooltip :content="scope.row.taskName" placement="top" :show-after="500">
                  <span class="task-name-text">{{ scope.row.taskName }}</span>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="processName" label="流程名称" min-width="120" max-width="160">
            <template #default="scope">
              <el-tooltip :content="scope.row.processName" placement="top" :show-after="500">
                <span class="process-name-text">{{ scope.row.processName }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          
          <el-table-column prop="priority" label="优先级" width="100">
            <template #default="scope">
              <el-tag :type="getPriorityType(scope.row.priority)" size="small">
                {{ getPriorityText(scope.row.priority) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="createTime" label="创建时间" width="160">
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          
          <el-table-column prop="dueDate" label="到期时间" width="160">
            <template #default="scope">
              <span :class="{ 'overdue': isOverdue(scope.row.dueDate) }">
                {{ formatDateTime(scope.row.dueDate) }}
              </span>
            </template>
          </el-table-column>
          
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status, scope.row)" size="small">
                {{ getStatusText(scope.row.status, scope.row) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="任务类型" width="180">
            <template #default="scope">
              <div class="task-type-cell">
                <!-- 横向显示：节点类型和签收信息 -->
                <div class="task-type-row">
                  <!-- 节点类型 -->
                  <el-tag 
                    :type="getTaskTypeTagType(scope.row)" 
                    size="small"
                    class="task-type-tag"
                  >
                    {{ getTaskTypeText(scope.row) }}
                  </el-tag>
                  
                  <!-- 签收信息 -->
                  <div v-if="isCandidateTask(scope.row)" class="claim-info">
                    <el-button
                      type="text"
                      size="small"
                      class="candidate-button"
                      @click="showCandidateUsers(scope.row)"
                    >
                      <Icon icon="ant-design:user-outlined" style="margin-right: 4px;" />
                      {{ getCandidateCount(scope.row) }}人待签收
                    </el-button>
                  </div>
                </div>
                
                <!-- 候选人用户列表 -->
                <div v-if="showInlineCandidateAvatars && getCandidateUsers(scope.row).length > 0" class="candidate-users">
                  <div 
                    v-for="user in getCandidateUsers(scope.row).slice(0, 3)" 
                    :key="user.id || user.userId"
                    class="candidate-user"
                  >
                    <UserInfo
                      :userId="user.id || user.userId"
                      :show-avatar="true"
                      :show-name="false"
                      :avatar-size="24"
                      :auto-load="true"
                    />
                  </div>
                  <span v-if="getCandidateUsers(scope.row).length > 3" class="more-users">
                    +{{ getCandidateUsers(scope.row).length - 3 }}
                  </span>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="220" fixed="right">
            <template #default="scope">
              <!-- 根据任务类型和状态显示不同的操作按钮 -->
              <template v-if="isCandidateTask(scope.row)">
                <!-- 候选人任务：显示签收按钮 -->
                <el-button
                  type="success"
                  size="small"
                  @click="handleClaimTask(scope.row)"
                >
                  <Icon icon="ant-design:check-outlined" />
                  签收
                </el-button>
              </template>
              <template v-else-if="isAssignedTask(scope.row)">
                <!-- 已分配任务：显示处理按钮 -->
                <el-button
                  type="primary"
                  size="small"
                  @click="handleProcessTask(scope.row)"
                >
                  <Icon icon="ant-design:play-circle-outlined" />
                  处理
                </el-button>
              </template>
              <template v-else>
                <!-- 其他状态：显示处理按钮 -->
                <el-button
                  type="primary"
                  size="small"
                  @click="handleProcessTask(scope.row)"
                >
                  <Icon icon="ant-design:play-circle-outlined" />
                  处理
                </el-button>
              </template>
              
              <el-button
                size="small"
                @click="handleViewDetail(scope.row)"
              >
                详情
              </el-button>
              
              <el-dropdown @command="(command) => handleCommand(command, scope.row)">
                <el-button size="small">
                  更多<Icon icon="ant-design:down-outlined" />
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <!-- 只有候选人任务才显示认领选项 -->
                    <el-dropdown-item 
                      v-if="isCandidateTask(scope.row)" 
                      command="claim"
                    >
                      认领
                    </el-dropdown-item>
                    <el-dropdown-item command="delegate">委派</el-dropdown-item>
                    <el-dropdown-item command="transfer">转办</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 流程详情弹窗（统一处理详情和处理模式） -->
    <ProcessDetailModal
      :key="`modal-${modalMode}-${selectedTask?.taskId || Date.now()}`"
      v-model:visible="modalVisible"
      :task-data="selectedTask"
      :mode="modalMode"
      @process-success="handleProcessSuccess"
    />

    <!-- 委派/转办弹窗 -->
    <SelectorModal
      v-model:visible="userSelectorVisible"
      type="user"
      :multiple="false"
      :selectedList="selectedUsers"
      @update:selectedList="handleUserSelect"
    />

    <!-- 候选人用户列表弹窗 -->
    <el-dialog
      v-model="candidateUsersVisible"
      title="候选人列表"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="candidate-users-dialog">
        <div v-if="currentCandidateUsers.length > 0" class="candidate-list">
          <div 
            v-for="user in currentCandidateUsers" 
            :key="user.id || user.userId"
            class="candidate-item"
          >
            <UserInfo
              :userId="user.id || user.userId"
              :show-avatar="true"
              :show-name="true"
              :show-account="true"
              :avatar-size="40"
              :auto-load="true"
            />
          </div>
        </div>
        <div v-else class="no-candidates">
          <el-empty description="暂无候选人信息" />
        </div>
      </div>
      <template #footer>
        <el-button @click="candidateUsersVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch, computed } from 'vue'
import Icon from '@/components/Icon/Icon.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMyTasks, claimTask, delegateTask, transferTask } from '@/api/workflow/process.api'
import SelectorModal from '@/components/Selector/SelectorModal.vue'
import ProcessDetailModal from '@/components/Workflow/ProcessDetailModal.vue'
import UserInfo from '@/components/UserInfo/index.vue' // 引入UserInfo组件

// 引入统一的夜间模式样式
import '@/components/Workflow/styles/dark-theme.css'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  taskName: '',
  processName: '',
  priority: '',
  createTime: [],
  status: '' // 新增状态筛选
})

// 高级筛选参数
const advancedQueryParams = reactive({
  dueTime: [],
  isOverdue: '',
  taskType: ''
})

// 显示高级筛选
const showAdvancedFilter = ref(false)

// 数据
const loading = ref(false)
const taskList = ref([])
const total = ref(0)
const selectedRows = ref([])

// 任务统计
const taskStats = reactive({
  pending: 0,
  overdue: 0,
  highPriority: 0,
  total: 0,
  candidate: 0, // 新增：候选人任务数量
  assigned: 0   // 新增：已分配任务数量
})

// 弹窗控制
const modalVisible = ref(false)
const modalMode = ref('task') // 只支持 'task' 模式，用于任务处理
const selectedTask = ref(null)
const userSelectorVisible = ref(false)
const userSelectorTitle = ref('')
const currentCommand = ref('')
const selectedUsers = ref([])

// 候选人用户列表弹窗控制
const candidateUsersVisible = ref(false)
const currentCandidateUsers = ref([])

// 控制是否在任务类型列中显示内联候选人头像
const showInlineCandidateAvatars = ref(false)

// 查询表单引用
const queryFormRef = ref()

// 获取待办任务列表
async function loadTaskList() {
  try {
    loading.value = true
    const params = {
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize,
      taskName: queryParams.taskName,
      processName: queryParams.processName,
      priority: queryParams.priority,
      status: queryParams.status // 添加状态筛选参数
    }
    
    // 处理时间范围
    if (queryParams.createTime && queryParams.createTime.length === 2) {
      params.startTime = queryParams.createTime[0]
      params.endTime = queryParams.createTime[1]
    }

    // 处理高级筛选参数
    if (advancedQueryParams.dueTime && advancedQueryParams.dueTime.length === 2) {
      params.dueTimeStart = advancedQueryParams.dueTime[0]
      params.dueTimeEnd = advancedQueryParams.dueTime[1]
    }
    if (advancedQueryParams.isOverdue) {
      params.isOverdue = advancedQueryParams.isOverdue === 'true'
    }
    if (advancedQueryParams.taskType) {
      params.taskType = advancedQueryParams.taskType
    }
    
    // 处理状态筛选参数
    if (queryParams.status) {
      if (queryParams.status === 'CREATED_CANDIDATE') {
        // 待签收状态：需要特殊处理，在客户端筛选
        params.status = 'CREATED'
        params.isCandidate = true
      } else {
        params.status = queryParams.status
      }
    }
    
    console.log('请求参数:', params)
    const response = await getMyTasks(params)
    console.log('待办任务API响应:', response)
    
    // defHttp会自动处理响应，当code=200时返回data字段的内容
    // 所以response直接就是TableDataInfo格式
    if (response && response.items) {
      let tasks = response.items || []
      total.value = response.total || 0
      console.log('获取到真实任务数量:', tasks.length)
      console.log('任务数据:', tasks)
      
      // 处理任务数据，解析流程变量
      tasks.forEach(task => {
        // 尝试解析流程变量
        if (task.variables) {
          try {
            if (typeof task.variables === 'string') {
              task.processVariables = JSON.parse(task.variables)
            } else {
              task.processVariables = task.variables
            }
            console.log(`任务 ${task.taskId} 的流程变量:`, task.processVariables)
          } catch (e) {
            console.warn(`解析任务 ${task.taskId} 的流程变量失败:`, e)
            task.processVariables = {}
          }
        }
        
        // 如果没有流程变量，尝试从assigneeConfig中获取信息
        if (!task.processVariables && task.assigneeConfig) {
          try {
            if (typeof task.assigneeConfig === 'string') {
              const assigneeConfig = JSON.parse(task.assigneeConfig)
              // 查找当前任务对应的配置
              const currentTaskConfig = assigneeConfig.find(config => 
                config.id === task.taskDefinitionKey || config.id === task.taskId
              )
              if (currentTaskConfig) {
                task.processVariables = {
                  taskStatus: 'CREATED', // 默认为待签收状态
                  nodeType: 'normal',    // 默认为普通节点
                  candidateUsers: currentTaskConfig.handlers || [],
                  candidateCount: currentTaskConfig.handlers ? currentTaskConfig.handlers.length : 0
                }
                console.log(`任务 ${task.taskId} 从assigneeConfig获取的流程变量:`, task.processVariables)
              }
            }
          } catch (e) {
            console.warn(`解析任务 ${task.taskId} 的assigneeConfig失败:`, e)
          }
        }
      })
      
      // 客户端筛选：处理不同状态的筛选
      if (queryParams.status) {
        if (queryParams.status === 'CREATED_CANDIDATE') {
          // 待签收状态：筛选候选人任务
          tasks = tasks.filter(task => isCandidateTask(task))
          total.value = tasks.length
          console.log('客户端筛选后的候选人任务数量:', tasks.length)
        } else if (queryParams.status === 'CREATED') {
          // 待认领状态：筛选非候选人任务
          tasks = tasks.filter(task => task.status === 'CREATED' && !isCandidateTask(task))
          total.value = tasks.length
          console.log('客户端筛选后的待认领任务数量:', tasks.length)
        } else if (queryParams.status === 'ASSIGNED') {
          // 已认领状态：筛选已分配任务
          tasks = tasks.filter(task => task.status === 'ASSIGNED')
          total.value = tasks.length
          console.log('客户端筛选后的已认领任务数量:', tasks.length)
        } else if (queryParams.status === 'PENDING') {
          // 进行中状态：筛选进行中任务
          tasks = tasks.filter(task => task.status === 'PENDING')
          total.value = tasks.length
          console.log('客户端筛选后的进行中任务数量:', tasks.length)
        } else if (queryParams.status === 'COMPLETED') {
          // 已完成状态：筛选已完成任务
          tasks = tasks.filter(task => task.status === 'COMPLETED')
          total.value = tasks.length
          console.log('客户端筛选后的已完成任务数量:', tasks.length)
        } else if (queryParams.status === 'CANCELLED') {
          // 已取消状态：筛选已取消任务
          tasks = tasks.filter(task => task.status === 'CANCELLED')
          total.value = tasks.length
          console.log('客户端筛选后的已取消任务数量:', tasks.length)
        }
      }
      
      taskList.value = tasks
    } else if (response && Array.isArray(response)) {
      // 兼容数组格式
      taskList.value = response
      total.value = response.length
      console.log('获取到任务数量(数组格式):', taskList.value.length)
    } else {
      console.warn('API返回数据格式异常，使用模拟数据')
      console.warn('响应内容:', response)
      // 使用模拟数据
      taskList.value = [
        {
          id: 1,
          taskId: 'task_001',
          taskName: '审批请假申请',
          processName: '请假流程',
          processInstanceId: 'PI_001',
          assignee: 'admin',
          createTime: new Date().toISOString(),
          dueDate: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
          priority: 1,
          status: 'PENDING'
        },
        {
          id: 2,
          taskId: 'task_002',
          taskName: '审核报销单',
          processName: '报销流程',
          processInstanceId: 'PI_002',
          assignee: 'admin',
          createTime: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(),
          dueDate: new Date(Date.now() + 48 * 60 * 60 * 1000).toISOString(),
          priority: 2,
          status: 'PENDING'
        }
      ]
      total.value = taskList.value.length
    }
    
    // 更新任务统计
    updateTaskStats()
  } catch (error) {
    console.error('获取待办任务失败:', error)
    ElMessage.error('获取待办任务失败: ' + (error.message || '未知错误'))
    // 使用模拟数据
    taskList.value = [
      {
        id: 1,
        taskId: 'task_001',
        taskName: '审批请假申请',
        processName: '请假流程',
        processInstanceId: 'PI_001',
        assignee: 'admin',
        createTime: new Date().toISOString(),
        dueDate: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
        priority: 1,
        status: 'PENDING'
      },
      {
        id: 2,
        taskId: 'task_002',
        taskName: '审核报销单',
        processName: '报销流程',
        processInstanceId: 'PI_002',
        assignee: 'admin',
        createTime: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(),
        dueDate: new Date(Date.now() + 48 * 60 * 60 * 1000).toISOString(),
        priority: 2,
        status: 'PENDING'
      }
    ]
    total.value = taskList.value.length
    updateTaskStats()
  } finally {
    loading.value = false
  }
}

// 更新任务统计
const updateTaskStats = () => {
  const now = new Date()
  
  // 统计候选人任务（待签收）
  taskStats.candidate = taskList.value.filter(task => 
    isCandidateTask(task)
  ).length
  
  // 统计已分配任务（已认领/进行中）
  taskStats.assigned = taskList.value.filter(task => 
    isAssignedTask(task)
  ).length
  
  // 统计待处理任务（候选人 + 已分配）
  taskStats.pending = taskStats.candidate + taskStats.assigned
  
  // 统计过期任务
  taskStats.overdue = taskList.value.filter(task => {
    if (!task.dueDate) return false
    return new Date(task.dueDate) < now
  }).length
  
  // 统计高优先级任务
  taskStats.highPriority = taskList.value.filter(task => 
    task.priority === 1 || task.priority === 'HIGH'
  ).length
  
  // 总任务数
  taskStats.total = taskList.value.length
  
  console.log('任务统计更新:', {
    candidate: taskStats.candidate,
    assigned: taskStats.assigned,
    pending: taskStats.pending,
    overdue: taskStats.overdue,
    total: taskStats.total
  })
}

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1
  loadTaskList()
}

// 重置查询
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  queryParams.pageNum = 1
  loadTaskList()
}

// 刷新列表
const refreshList = () => {
  loadTaskList()
}

// 分页处理
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  loadTaskList()
}

const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  loadTaskList()
}

// 选择处理
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
  console.log('选中任务变化:', {
    count: selection.length,
    tasks: selection.map(t => ({ 
      taskId: t.taskId, 
      taskName: t.taskName, 
      isCandidate: isCandidateTask(t),
      status: t.status 
    }))
  })
}

// 获取优先级类型
const getPriorityType = (priority) => {
  const typeMap = {
    1: 'danger',
    2: 'warning',
    3: 'info'
  }
  return typeMap[priority] || 'info'
}

// 获取优先级文本
const getPriorityText = (priority) => {
  const textMap = {
    1: '高',
    2: '中',
    3: '低'
  }
  return textMap[priority] || '普通'
}

// 判断是否为候选人任务
const isCandidateTask = (task) => {
  console.log('isCandidateTask - 检查任务:', {
    taskId: task.taskId,
    status: task.status,
    assignee: task.assignee,
    candidateUsers: task.candidateUsers,
    processVariables: task.processVariables
  })
  
  // 1. 优先从流程变量中判断候选人任务
  if (task.processVariables) {
    const taskStatus = task.processVariables.taskStatus
    const candidateUsers = task.processVariables.candidateUsers
    const candidateCount = task.processVariables.candidateCount
    const assignee = task.processVariables.assignee
    
    console.log('isCandidateTask - 流程变量检查:', {
      taskStatus,
      candidateUsers,
      candidateCount,
      assignee
    })
    
    // 如果流程变量明确标识为已分配任务
    if (taskStatus === 'ASSIGNED' && assignee) {
      console.log('isCandidateTask - 从流程变量判断为已分配任务')
      return false
    }
    
    // 如果流程变量明确标识为候选人任务
    if (taskStatus === 'CREATED' && candidateUsers && candidateUsers.length > 0) {
      console.log('isCandidateTask - 从流程变量判断为候选人任务')
      return true
    }
  }
  
  // 2. 从任务状态和候选人信息判断
  // 候选人任务：状态为CREATED且没有指定处理人，或者有多个候选人
  const isCandidate = (task.status === 'CREATED' && !task.assignee) || 
         (task.status === 'CREATED' && task.candidateUsers && task.candidateUsers.length > 0) ||
         // 从任务属性中判断候选人任务
         (task.candidateUsers && task.candidateUsers.length > 0 && !task.assignee)
  
  console.log('isCandidateTask - 最终判断结果:', isCandidate)
  return isCandidate
}

// 判断是否为已分配任务
const isAssignedTask = (task) => {
  console.log('isAssignedTask - 检查任务:', {
    taskId: task.taskId,
    status: task.status,
    assignee: task.assignee,
    processVariables: task.processVariables
  })
  
  // 1. 优先从流程变量中判断已分配任务
  if (task.processVariables) {
    const taskStatus = task.processVariables.taskStatus
    const assignee = task.processVariables.assignee
    
    console.log('isAssignedTask - 流程变量检查:', {
      taskStatus,
      assignee
    })
    
    // 如果流程变量明确标识为已分配任务
    if (taskStatus === 'ASSIGNED' && assignee) {
      console.log('isAssignedTask - 从流程变量判断为已分配任务')
      return true
    }
    
    // 如果流程变量明确标识为候选人任务
    if (taskStatus === 'CREATED' && task.processVariables.candidateUsers && task.processVariables.candidateUsers.length > 0) {
      console.log('isAssignedTask - 从流程变量判断为候选人任务')
      return false
    }
  }
  
  // 2. 从任务状态判断
  const isAssigned = task.status === 'ASSIGNED' || task.status === 'PENDING' ||
         // 有指定处理人的任务
         (task.assignee && task.assignee !== '')
  
  console.log('isAssignedTask - 最终判断结果:', isAssigned)
  return isAssigned
}

// 判断是否为会签节点任务
const isCountersignTask = (task) => {
  return task.taskType === 'countersign' || 
         (task.processVariables && task.processVariables.countersignType) ||
         // 新增：从流程变量中判断会签节点
         (task.processVariables && task.processVariables.isCountersign === true)
}

// 获取任务状态文本（增强版）
const getStatusText = (status, task) => {
  // 优先从流程变量中获取状态
  if (task.processVariables && task.processVariables.taskStatus) {
    const taskStatus = task.processVariables.taskStatus
    if (taskStatus === 'CREATED') {
      return '待签收'
    } else if (taskStatus === 'ASSIGNED') {
      return '已认领'
    } else if (taskStatus === 'PENDING') {
      return '进行中'
    }
  }
  
  // 从任务状态判断
  if (isCandidateTask(task)) {
    return '待签收'
  }
  
  const textMap = {
    'CREATED': '待认领',
    'ASSIGNED': '已认领',
    'PENDING': '进行中',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  }
  return textMap[status] || status
}

// 获取任务状态类型（增强版）
const getStatusType = (status, task) => {
  // 优先从流程变量中获取状态类型
  if (task.processVariables && task.processVariables.taskStatus) {
    const taskStatus = task.processVariables.taskStatus
    if (taskStatus === 'CREATED') {
      return 'warning' // 候选人任务使用警告色
    } else if (taskStatus === 'ASSIGNED') {
      return 'primary' // 已认领任务使用主色
    } else if (taskStatus === 'PENDING') {
      return 'success' // 进行中任务使用成功色
    }
  }
  
  // 从任务状态判断
  if (isCandidateTask(task)) {
    return 'warning' // 候选人任务使用警告色
  }
  
  const typeMap = {
    'CREATED': 'info',
    'ASSIGNED': 'primary',
    'PENDING': 'success',
    'COMPLETED': 'success',
    'CANCELLED': 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取任务类型文本
const getTaskTypeText = (task) => {
  // 优先从流程变量中获取节点类型
  if (task.processVariables && task.processVariables.nodeType) {
    const nodeType = task.processVariables.nodeType
    if (nodeType === 'normal') {
      return '普通节点'
    } else if (nodeType === 'countersign') {
      return '会签节点'
    }
  }
  
  // 从任务类型判断
  if (task.taskType === 'userTask' || task.taskType === 'USER_TASK') {
    return '用户任务'
  } else if (task.taskType === 'serviceTask' || task.taskType === 'SERVICE_TASK') {
    return '服务任务'
  } else if (task.taskType === 'scriptTask' || task.taskType === 'SCRIPT_TASK') {
    return '脚本任务'
  } else {
    return '未知任务'
  }
}

// 获取任务类型标签类型
const getTaskTypeTagType = (task) => {
  // 优先从流程变量中获取节点类型标签
  if (task.processVariables && task.processVariables.nodeType) {
    const nodeType = task.processVariables.nodeType
    if (nodeType === 'normal') {
      return 'success'
    } else if (nodeType === 'countersign') {
      return 'warning'
    }
  }
  
  // 从任务类型判断
  if (task.taskType === 'userTask' || task.taskType === 'USER_TASK') {
    return 'success'
  } else if (task.taskType === 'serviceTask' || task.taskType === 'SERVICE_TASK') {
    return 'info'
  } else if (task.taskType === 'scriptTask' || task.taskType === 'SCRIPT_TASK') {
    return 'warning'
  } else {
    return 'info'
  }
}

// 格式化日期时间
const formatDateTime = (time) => {
  if (!time) return '-'
  
  try {
    // 处理数组格式的时间（后端返回的格式）
    if (Array.isArray(time)) {
      // 数组格式：[year, month, day, hour, minute, second, nanosecond]
      if (time.length >= 6) {
        const [year, month, day, hour, minute, second] = time
        // 注意：月份从0开始，所以需要减1
        const date = new Date(year, month - 1, day, hour, minute, second)
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })
      }
    }
    
    // 处理标准时间格式
    const date = new Date(time)
    if (isNaN(date.getTime())) {
      return '-'
    }
    
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error) {
    console.warn('时间格式化失败:', error, '原始值:', time)
    return '-'
  }
}

// 判断是否过期
const isOverdue = (dueDate) => {
  if (!dueDate) return false
  return new Date(dueDate) < new Date()
}

// 处理任务
const handleProcessTask = (task) => {
  // 先设置任务数据，再显示弹窗
  selectedTask.value = { ...task }
  modalMode.value = 'task' // 使用task模式处理任务，支持表单编辑和审批操作
  nextTick(() => {
    modalVisible.value = true
  })
}

// 查看详情
const handleViewDetail = (task) => {
  selectedTask.value = { ...task }
  // 如果是候选人任务或已分配任务，使用task模式，显示审批操作（提交/重置）
  if (isCandidateTask(task) || isAssignedTask(task)) {
    modalMode.value = 'task'
  } else {
    modalMode.value = 'view'
  }
  nextTick(() => {
    modalVisible.value = true
  })
}

// 处理下拉菜单命令
const handleCommand = (command, task) => {
  selectedTask.value = task
  currentCommand.value = command // 记录当前命令
  
  switch (command) {
    case 'claim':
      handleClaimTask(task)
      break
    case 'delegate':
      userSelectorVisible.value = true
      userSelectorTitle.value = '委派用户'
      break
    case 'transfer':
      userSelectorVisible.value = true
      userSelectorTitle.value = '转办用户'
      break
  }
}

// 认领任务
const handleClaimTask = async (task) => {
  try {
    const confirmMessage = isCandidateTask(task) 
      ? '确定要签收此任务吗？签收后其他候选人将无法看到此任务。' 
      : '确定要认领此任务吗？'
    
    await ElMessageBox.confirm(confirmMessage, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 使用taskId而不是id
    await claimTask(task.taskId)
    
    const successMessage = isCandidateTask(task) ? '任务签收成功' : '任务认领成功'
    ElMessage.success(successMessage)
    
    // 更新本地任务状态（优化用户体验）
    if (isCandidateTask(task)) {
      // 如果是候选人任务，更新为已分配状态
      if (task.processVariables) {
        task.processVariables.taskStatus = 'ASSIGNED'
        task.processVariables.assignee = 'current_user' // 设置当前用户为处理人
      }
      // 设置当前用户为处理人
      task.assignee = 'current_user' // 这里应该设置为实际的当前用户ID
      task.status = 'ASSIGNED'
      
      // 立即更新UI显示
      nextTick(() => {
        // 强制重新渲染该行
        const index = taskList.value.findIndex(t => t.taskId === task.taskId)
        if (index !== -1) {
          taskList.value[index] = { ...taskList.value[index] }
        }
      })
    }
    
    // 刷新任务列表
    await loadTaskList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
      const errorMessage = isCandidateTask(task) ? '签收任务失败' : '认领任务失败'
      ElMessage.error(errorMessage + ': ' + (error.message || '未知错误'))
    }
  }
}

// 处理用户选择
const handleUserSelect = async (users) => {
  try {
    if (!users || users.length === 0) return
    
    const userId = users[0].id // 取第一个用户
    if (currentCommand.value === 'delegate') {
      // 使用taskId而不是id
      await delegateTask(selectedTask.value.taskId, userId)
      ElMessage.success('任务委派成功')
    } else if (currentCommand.value === 'transfer') {
      // 使用taskId而不是id
      await transferTask(selectedTask.value.taskId, userId)
      ElMessage.success('任务转办成功')
    }
    userSelectorVisible.value = false
    selectedUsers.value = [] // 清空选择
    loadTaskList()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 处理任务成功
const handleProcessSuccess = () => {
  modalVisible.value = false
  loadTaskList()
}

// 批量认领
const handleBatchClaim = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要批量认领的任务')
    return
  }

  try {
    // 检查选中的任务类型
    const candidateTasks = selectedRows.value.filter(task => isCandidateTask(task))
    const normalTasks = selectedRows.value.filter(task => !isCandidateTask(task))
    
    let confirmMessage = `确定要批量处理选中的 ${selectedRows.value.length} 个任务吗？`
    if (candidateTasks.length > 0) {
      confirmMessage += `\n其中 ${candidateTasks.length} 个为候选人任务（签收），${normalTasks.length} 个为普通任务（认领）`
    }
    
    await ElMessageBox.confirm(confirmMessage, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    let successCount = 0
    let failCount = 0
    
    for (const task of selectedRows.value) {
      try {
        await claimTask(task.taskId)
        successCount++
        
        // 更新本地任务状态
        if (isCandidateTask(task)) {
          if (task.processVariables) {
            task.processVariables.taskStatus = 'ASSIGNED'
          }
          task.assignee = 'current_user'
          task.status = 'ASSIGNED'
        }
      } catch (error) {
        console.error(`任务 ${task.taskId} 操作失败:`, error)
        failCount++
      }
    }
    
    // 显示结果
    if (failCount === 0) {
      ElMessage.success(`成功批量处理 ${successCount} 个任务`)
    } else {
      ElMessage.warning(`批量处理完成：成功 ${successCount} 个，失败 ${failCount} 个`)
    }
    
    // 刷新任务列表
    await loadTaskList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量操作失败:', error)
      ElMessage.error('批量操作失败: ' + (error.message || '未知错误'))
    }
  }
}

// 批量委派
const handleBatchDelegate = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要批量委派的任务')
    return
  }

  userSelectorVisible.value = true
  userSelectorTitle.value = '批量委派用户'
  selectedUsers.value = selectedRows.value.map(task => ({ id: task.assignee, name: task.assignee }))
}

// 批量操作权限控制
const canBatchClaim = computed(() => {
  if (selectedRows.value.length === 0) return false
  
  // 检查选中的任务是否都可以操作
  return selectedRows.value.every(task => {
    // 候选人任务：可以签收
    if (isCandidateTask(task)) {
      return true
    }
    // 普通任务：状态为CREATED且没有处理人的可以认领
    if (task.status === 'CREATED' && !task.assignee) {
      return true
    }
    return false
  })
})

// 获取批量操作文本
const getBatchActionText = () => {
  const candidateTasks = selectedRows.value.filter(task => isCandidateTask(task))
  const normalTasks = selectedRows.value.filter(task => !isCandidateTask(task))

  if (candidateTasks.length > 0 && normalTasks.length > 0) {
    return '批量处理'
  } else if (candidateTasks.length > 0) {
    return '批量签收'
  } else if (normalTasks.length > 0) {
    return '批量认领'
  }
  return '批量处理' // 默认值
}

// 切换高级筛选
const toggleAdvancedFilter = () => {
  showAdvancedFilter.value = !showAdvancedFilter.value
}

// 获取候选人数量
const getCandidateCount = (task) => {
  // 优先从流程变量中获取
  if (task.processVariables && task.processVariables.candidateCount) {
    return task.processVariables.candidateCount
  }
  if (task.processVariables && task.processVariables.candidateUsers && task.processVariables.candidateUsers.length > 0) {
    return task.processVariables.candidateUsers.length
  }
  
  // 从任务属性中获取
  if (task.candidateUsers && task.candidateUsers.length > 0) {
    return task.candidateUsers.length
  }
  
  // 从assigneeConfig中获取
  if (task.assigneeConfig) {
    try {
      const assigneeConfig = typeof task.assigneeConfig === 'string' ? 
        JSON.parse(task.assigneeConfig) : task.assigneeConfig
      const currentTaskConfig = assigneeConfig.find(config => 
        config.id === task.taskDefinitionKey || config.id === task.taskId
      )
      if (currentTaskConfig && currentTaskConfig.handlers) {
        return currentTaskConfig.handlers.length
      }
    } catch (e) {
      console.warn(`解析assigneeConfig失败:`, e)
    }
  }
  
  return 0
}

// 获取候选人用户信息文本 (同步版本)
const getCandidateUsersTextSync = (task) => {
  const users = []
  
  // 1. 优先从流程变量中获取
  if (task.processVariables && task.processVariables.candidateUsers) {
    // 处理字符串数组格式的候选人
    if (Array.isArray(task.processVariables.candidateUsers)) {
      task.processVariables.candidateUsers.forEach(userId => {
        if (typeof userId === 'string') {
          // 如果是字符串ID，直接使用
          users.push(userId)
        } else if (typeof userId === 'object') {
          // 如果是对象，提取名称
          const userName = userId.userName || userId.nickName || userId.name || userId.id || userId.account
          if (userName) {
            users.push(userName)
          }
        }
      })
    }
  }
  
  // 2. 从任务属性中获取
  if (task.candidateUsers && task.candidateUsers.length > 0) {
    task.candidateUsers.forEach(user => {
      if (typeof user === 'string') {
        users.push(user)
      } else if (typeof user === 'object') {
        const userName = user.userName || user.nickName || user.name || user.id || user.account
        if (userName) {
          users.push(userName)
        }
      }
    })
  }
  
  // 3. 从assigneeConfig中获取
  if (task.assigneeConfig) {
    try {
      const assigneeConfig = typeof task.assigneeConfig === 'string' ? 
        JSON.parse(task.assigneeConfig) : task.assigneeConfig
      
      // 查找当前任务对应的配置
      const currentTaskConfig = assigneeConfig.find(config => 
        config.id === task.taskDefinitionKey || config.id === task.taskId
      )
      
      if (currentTaskConfig && currentTaskConfig.handlers) {
        currentTaskConfig.handlers.forEach(user => {
          if (typeof user === 'string') {
            users.push(user)
          } else if (typeof user === 'object') {
            const userName = user.userName || user.nickName || user.name || user.id || user.account
            if (userName) {
              users.push(userName)
            }
          }
        })
      }
    } catch (e) {
      console.warn(`解析assigneeConfig失败:`, e)
    }
  }
  
  // 4. 如果还是没有候选人信息，尝试从其他字段获取
  if (users.length === 0) {
    // 尝试从任务的其他属性中获取
    if (task.candidateGroups && task.candidateGroups.length > 0) {
      users.push(...task.candidateGroups)
    }
    
    // 尝试从任务定义中获取
    if (task.taskDefinitionKey) {
      console.log('尝试从任务定义获取候选人:', task.taskDefinitionKey)
    }
  }
  
  // 去重并返回
  const uniqueUsers = [...new Set(users)]
  console.log('最终候选人列表:', uniqueUsers)
  
  return uniqueUsers.length > 0 ? uniqueUsers.join(', ') : '暂无候选人信息'
}

// 获取候选人用户列表
const getCandidateUsers = (task) => {
  const users = []
  
  console.log('getCandidateUsers - 处理任务:', {
    taskId: task.taskId,
    processVariables: task.processVariables,
    candidateUsers: task.candidateUsers,
    assigneeConfig: task.assigneeConfig
  })
  
  // 1. 优先从流程变量中获取
  if (task.processVariables && task.processVariables.candidateUsers) {
    console.log('从processVariables获取候选人用户:', task.processVariables.candidateUsers)
    
    // 处理字符串数组格式的候选人
    if (Array.isArray(task.processVariables.candidateUsers)) {
      task.processVariables.candidateUsers.forEach(userId => {
        if (typeof userId === 'string') {
          // 如果是字符串ID，创建用户对象
          users.push({
            id: userId,
            userName: userId,
            nickName: userId,
            name: userId
          })
        } else if (typeof userId === 'object') {
          users.push(userId)
        }
      })
    }
  }
  
  // 2. 从任务属性中获取
  if (task.candidateUsers && task.candidateUsers.length > 0) {
    console.log('从candidateUsers获取候选人用户:', task.candidateUsers)
    task.candidateUsers.forEach(user => {
      if (typeof user === 'string') {
        users.push({
          id: user,
          userName: user,
          nickName: user,
          name: user
        })
      } else if (typeof user === 'object') {
        users.push(user)
      }
    })
  }
  
  // 3. 从assigneeConfig中获取
  if (task.assigneeConfig) {
    try {
      const assigneeConfig = typeof task.assigneeConfig === 'string' ? 
        JSON.parse(task.assigneeConfig) : task.assigneeConfig
      
      console.log('解析assigneeConfig获取用户:', assigneeConfig)
      
      // 查找当前任务对应的配置
      const currentTaskConfig = assigneeConfig.find(config => 
        config.id === task.taskDefinitionKey || config.id === task.taskId
      )
      
      if (currentTaskConfig && currentTaskConfig.handlers) {
        console.log('从assigneeConfig获取候选人用户:', currentTaskConfig.handlers)
        currentTaskConfig.handlers.forEach(user => {
          if (typeof user === 'string') {
            users.push({
              id: user,
              userName: user,
              nickName: user,
              name: user
            })
          } else if (typeof user === 'object') {
            users.push(user)
          }
        })
      }
    } catch (e) {
      console.warn(`解析assigneeConfig失败:`, e)
    }
  }
  
  // 4. 如果还是没有候选人信息，尝试从其他字段获取
  if (users.length === 0) {
    // 尝试从任务的其他属性中获取
    if (task.candidateGroups && task.candidateGroups.length > 0) {
      // 将组转换为用户对象
      task.candidateGroups.forEach(groupId => {
        users.push({
          id: groupId,
          name: `组: ${groupId}`,
          type: 'group'
        })
      })
    }
    
    // 尝试从任务定义中获取
    if (task.taskDefinitionKey) {
      console.log('尝试从任务定义获取候选人:', task.taskDefinitionKey)
    }
  }
  
  // 去重并返回
  const uniqueUsers = []
  const seenIds = new Set()
  users.forEach(user => {
    const userId = user.id || user.userId
    if (userId && !seenIds.has(userId)) {
      seenIds.add(userId)
      uniqueUsers.push(user)
    } else if (!userId) {
      // 如果没有ID，使用名称作为唯一标识
      const userName = user.userName || user.nickName || user.name || user.account
      if (userName && !seenIds.has(userName)) {
        seenIds.add(userName)
        uniqueUsers.push(user)
      }
    }
  })
  
  console.log('最终候选人用户列表:', uniqueUsers)
  return uniqueUsers
}

// 显示候选人用户列表弹窗
const showCandidateUsers = (task) => {
  showCandidateUsersDialog(task)
}

// 显示候选人用户列表弹窗
const showCandidateUsersDialog = (task) => {
  currentCandidateUsers.value = getCandidateUsers(task)
  candidateUsersVisible.value = true
}

onMounted(() => {
  loadTaskList()
})
</script>

<style scoped>
.todo-container {
  padding: 24px;
  background: #f5f5f5;
  min-height: calc(100vh - 120px);
}

.page-header {
  margin-bottom: 24px;
  text-align: center;
}

.page-header h2 {
  font-size: 28px;
  font-weight: 600;
  color: #1a1a1a;
  margin-bottom: 8px;
}

.page-header p {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.filter-section {
  margin-bottom: 24px;
}

.advanced-filter {
  margin-top: 15px;
  padding-left: 20px;
}

.stats-section {
  margin-bottom: 24px;
}

.stat-card {
  text-align: center;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
}

.stat-icon {
  font-size: 32px;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-icon.pending {
  background-color: #e6f7ff;
  color: #1890ff;
}

.stat-icon.overdue {
  background-color: #fff2e8;
  color: #fa541c;
}

.stat-icon.high {
  background-color: #fff1f0;
  color: #f5222d;
}

.stat-icon.total {
  background-color: #f6ffed;
  color: #52c41a;
}

.stat-icon.candidate {
  background-color: #e1f3d8;
  color: #67c23a;
}

.stat-icon.candidate:hover {
  background-color: #d1ecf1;
  color: #5aad5a;
}

.stat-info {
  text-align: left;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

/* 统计卡片详情样式 */
.stat-detail {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}

.detail-item {
  margin-right: 8px;
  padding: 2px 6px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 3px;
  display: inline-block;
  font-size: 11px;
  color: #606266;
  border: 1px solid #e4e7ed;
}

.detail-item:last-child {
  margin-right: 0;
}

/* 候选人统计卡片样式 */
.stat-icon.candidate {
  background-color: #e1f3d8;
  color: #67c23a;
}

.stat-icon.candidate:hover {
  background-color: #d1ecf1;
  color: #5aad5a;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.task-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
  max-width: 100%;
}

.task-icon {
  color: #409eff;
  font-size: 16px;
  flex-shrink: 0;
}

.overdue {
  color: #f56c6c;
  font-weight: 500;
}

/* 任务名称和流程名称文本样式 */
.task-name-text,
.process-name-text {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 任务状态样式 */
.task-status {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.task-status-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
}

.task-status-dot.pending {
  background-color: #e6a23c;
}

.task-status-dot.assigned {
  background-color: #409eff;
}

.task-status-dot.completed {
  background-color: #67c23a;
}

/* 优先级样式 */
.priority-high {
  background-color: #fef0f0;
  color: #f56c6c;
  border: 1px solid #fbc4c4;
}

.priority-medium {
  background-color: #fdf6ec;
  color: #e6a23c;
  border: 1px solid #f5dab1;
}

.priority-low {
  background-color: #f0f9ff;
  color: #409eff;
  border: 1px solid #b3d8ff;
}

/* 任务类型单元格样式 */
.task-type-cell {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 4px;
  min-height: auto;
  justify-content: flex-start;
  max-width: 100%;
}

/* 横向显示：节点类型和签收信息 */
.task-type-row {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.task-type-tag {
  flex-shrink: 0;
  height: 24px;
  line-height: 24px;
}

.claim-info {
  display: flex;
  align-items: center;
  gap: 4px;
}

.candidate-button {
  color: #67c23a;
  font-size: 12px;
  padding: 0 4px;
  height: 24px;
  line-height: 24px;
  display: inline-flex;
  align-items: center;
}

.candidate-button:hover {
  background-color: #e1f3d8;
  color: #67c23a;
}

/* 候选人用户列表弹窗样式 */
.candidate-users-dialog {
  max-height: 400px;
  overflow-y: auto;
}

.candidate-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.candidate-item {
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background-color: #fafafa;
  transition: all 0.2s ease;
}

.candidate-item:hover {
  background-color: #f0f9ff;
  border-color: #409eff;
}

.no-candidates {
  text-align: center;
  padding: 40px 0;
}

/* 候选人信息样式 */
.candidate-info {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 4px;
  margin-top: 4px;
  font-size: 12px;
}

.candidate-count {
  color: #67c23a;
  background-color: #f0f9ff;
  padding: 2px 6px;
  border-radius: 3px;
  border: 1px solid #d1ecf1;
  cursor: help;
  display: flex;
  align-items: center;
  gap: 2px;
}

.candidate-count:hover {
  background-color: #e1f3d8;
  border-color: #c3e6cb;
}

/* 候选人用户列表样式 */
.candidate-users {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-top: 4px;
}

.candidate-user {
  cursor: pointer;
  transition: transform 0.2s;
}

.candidate-user:hover {
  transform: scale(1.1);
}

.more-users {
  font-size: 11px;
  color: #909399;
  background-color: #f5f7fa;
  padding: 2px 6px;
  border-radius: 10px;
  border: 1px solid #e4e7ed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .todo-container {
    padding: 16px;
  }
  
  .page-header h2 {
    font-size: 24px;
  }
  
  .filter-section .el-form-item {
    margin-bottom: 12px;
  }
  
  .task-section .el-table {
    font-size: 12px;
  }
}

/* 夜间模式支持 */
:deep(.dark) .todo-container {
  background: #1a1a1a;
}

:deep(.dark) .page-header h2 {
  color: #ffffff;
}

:deep(.dark) .page-header p {
  color: #a0a0a0;
}

:deep(.dark) .task-icon {
  color: #409eff;
}

:deep(.dark) .overdue {
  color: #f56c6c;
}

/* 确保按钮可以正常点击 */
:deep(.el-button) {
  pointer-events: auto !important;
  cursor: pointer !important;
}

:deep(.el-dropdown) {
  pointer-events: auto !important;
}

:deep(.el-dropdown-menu__item) {
  pointer-events: auto !important;
  cursor: pointer !important;
}
</style> 